﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Web.Mvc;
using System.Web.UI;
using UFIDA.U9.Base.BaseBE.Util;
using UFIDA.U9.Cust.Pub.WebSocketSharp.Server;
using UFSoft.UBF.AopFrame.Lock;
using UFSoft.UBF.Cust.ClassView.MVC.Debug;
using UFSoft.UBF.Cust.ClassView.MVC.Metedata;
using UFSoft.UBF.Cust.ClassView.MVC.OQL;
using UFSoft.UBF.Cust.ClassView.MVC.Proxy;
using UFSoft.UBF.Cust.ClassView.MVC.Query;
using UFSoft.UBF.Cust.ClassView.MVC.SQL;
using UFSoft.UBF.Cust.ClassView.MVC.UI;
using UFSoft.UBF.Cust.ClassView.MVC.Utils;
using UFSoft.UBF.Cust.ClassView.MVC.WebSocket;
using UFSoft.UBF.MVC;
using UFSoft.UBF.Service.Base;
using UFSoft.UBF.Sys.Database;
using UFSoft.UBF.UI.Portal.Components;
using UFSoft.UBF.Util.Context;
using UFSoft.UBF.Util.DataAccess;
using UFSoft.UBF.Util.Log;

namespace UFSoft.UBF.Cust.ClassView.MVC
{
    [AllowAnonymous]
    public class ClassViewController : BaseController
    {
        private const string Version = "1.2.5";
        private static readonly ILogger logger = LoggerManager.GetLogger(typeof(ClassViewController));

        static ClassViewController()
        {
            try
            {
                //替换服务校验服务
                WSSPortalSiteKeyProvider.ReplaceServiceCheckProvider();
            }
            catch (Exception ex)
            {
                logger.Error("ClassView初始化异常");
                logger.Error(ex);
            }
        }

        [HttpGet]
        public ActionResult Index()
        {
            return PartialView("~/ClassView/views/index.cshtml");
        }

        [HttpGet]
        public ActionResult Index100()
        {
            return PartialView("~/ClassView/views/index100.cshtml");
        }

        /// <summary>
        ///     获取上下文数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCurrentContext()
        {
            try
            {
                CSContext.Current.Transfer();
                Dictionary<string, string> data = null;
                if (PlatformContext.Current != null)
                {
                    data = new Dictionary<string, string>();
                    data.Add("EnterpriseID", PlatformContext.Current.EnterpriseID);
                    data.Add("EnterpriseName", PlatformContext.Current.EnterpriseName);
                    data.Add("OrgID", PlatformContext.Current.OrgID);
                    data.Add("OrgCode", PlatformContext.Current.OrgCode);
                    data.Add("OrgName", PlatformContext.Current.OrgName);
                    data.Add("UserID", PlatformContext.Current.UserID);
                    data.Add("UserCode", PlatformContext.Current.UserCode);
                    data.Add("UserName", PlatformContext.Current.UserName);
                    data.Add("Culture", PlatformContext.Current.Culture);
                    data.Add("Default_Culture", PlatformContext.Current.Default_Culture);
                    data.Add("Support_CultureName_List", PlatformContext.Current.Support_CultureName_List);
                    data.Add("EffectiveLanguageCount", PlatformContext.Current.EffectiveLanguageCount.ToString());
                    data.Add("LoginDate", PlatformContext.Current.LoginDate.ToShortDateString());
                    data.Add("LoginDateTime", PlatformContext.Current.LoginDateTime.ToLongDateString());
                    data.Add("LoginUBFDateTime", PlatformContext.Current.LoginUBFDateTime.ToLongDateString());
                    data.Add("OperationDate", PlatformContext.Current.OperationDate.ToLongDateString());
                    data.Add("MainThreadID", PlatformContext.Current.MainThreadID);
                    data.Add("TimeZone", PlatformContext.Current.TimeZone);
                    data.Add("UserClientIP", PlatformContext.Current.UserClientIP);
                    data.Add("Version", Version);
                }

                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("获取登录信息报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        #region 扩展字段

        /// <summary>
        ///     同步组合名称
        /// </summary>
        /// <returns></returns>
        public ActionResult SyncFieldCombineName()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                string entityFullName = Request["entityFullName"];
                string descFieldName = Request["descFieldName"];
                if (string.IsNullOrEmpty(entityFullName))
                    throw new Exception("entityFullName is empty");
                if (string.IsNullOrEmpty(descFieldName))
                    throw new Exception("descFieldName is empty");
                string spName = "P_SyncFieldCombineName";
                DataParamList dataParams = new DataParamList();
                dataParams.Add(DataParamFactory.CreateInput("FullName", entityFullName, DbType.String));
                dataParams.Add(DataParamFactory.CreateInput("DescFieldName", descFieldName, DbType.String));
                DataAccessor.RunSP(string.Format("dbo.{0}", spName), dataParams);
                return Json(new
                {
                    code = 0,
                    msg = "执行成功"
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("同步组合名称报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region CustomProxy

        /// <summary>
        ///     是否启用自定义代理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult IsSetupCustomProxy()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                Type managerType = GetCustomProxyManagerType();
                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    setupCustomProxy = managerType != null
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("是否启用自定义代理报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message,
                    setupCustomProxy = false
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///     获取自定义代理管理类型
        /// </summary>
        /// <returns></returns>
        private static Type GetCustomProxyManagerType()
        {
            string dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin\\UFIDA.U9.WSS.ProxyService.dll");
            if (!System.IO.File.Exists(dllPath)) return null;
            Assembly assembly = Assembly.LoadFrom(dllPath);
            return assembly.GetType("UFIDA.U9.WSS.ProxyService.CustomProxy.CustomProxyManager");
        }

        #endregion

        #region Enum

        /// <summary>
        ///     刷新全部枚举
        /// </summary>
        /// <returns></returns>
        public ActionResult RefreshAllEnum()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                using (new BPForEngine())
                {
                    //刷新枚举
                    SQLFuncHelper.RefreshAllEnum();
                    //清空缓存
                    GetEnumName.Reload();
                    return Json(new
                    {
                        code = 0,
                        msg = "执行成功"
                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error("刷新全部枚举报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///     刷新全部枚举
        /// </summary>
        /// <returns></returns>
        public ActionResult RefreshSingleEnum()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                string enumFullName = Request["enumFullName"];
                using (new BPForEngine())
                {
                    if (!string.IsNullOrEmpty(enumFullName))
                    {
                        //刷新枚举
                        SQLFuncHelper.RefreshSingleEnum(enumFullName);
                        //清空缓存
                        GetEnumName.Reload();
                    }

                    return Json(new
                    {
                        code = 0,
                        msg = "执行成功"
                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error("刷新单个枚举报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region UI

        /// <summary>
        ///     参照查询
        /// </summary>
        /// <returns></returns>
        public ActionResult QueryRef()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                List<RefDTO> data = new List<RefDTO>();
                string queryString = Request["queryString"];
                string strLike = Request["like"];
                bool isLike;
                bool.TryParse(strLike, out isLike);
                if (!string.IsNullOrWhiteSpace(queryString))
                {
                    queryString = queryString.Trim();
                    string strSql = string.Format(@"
SELECT C.ID AS ID,
       B.ID AS ComponentID,
       B.Name AS Name,
       D.DisplayName AS DisplayName,
       A.ClassName AS ClassName,
       A.FormId AS FormId,
       A.[Assembly] AS AssemblyName,
       A.URI AS URI,
       C.Filter AS Filter,
       C.RefEntityId AS RefEntityId,
       C.RefEntityName AS RefEntityName,
       B.IsMultiSelect AS IsMultiSelect,
       B.ForMultOrg AS ForMultOrg
FROM aspnet_Parts A
    INNER JOIN UBF_MD_UIRComponent B --UI参照组件
        ON A.URI = B.URI
    LEFT JOIN UBF_MD_UIReference C --UI组件
        ON B.ID = C.UIReferenceComponent
    LEFT JOIN UBF_MD_UIRComponent_Trl D
        ON B.ID = D.ID
           AND D.SysMLFlag = '{0}'", PlatformContext.Current.Culture);
                    if (isLike)
                    {
                        strSql += string.Format(@" WHERE C.RefEntityName LIKE '%{0}%'
                            OR D.DisplayName LIKE '%{0}%'
                            OR A.FormId LIKE '%{0}%'", queryString);
                    }
                    else
                    {
                        strSql += string.Format(@" WHERE C.RefEntityName = '{0}'
                            OR D.DisplayName = '{0}'
                            OR A.FormId = '{0}'", queryString);
                    }

                    strSql += " ORDER BY B.Name,A.ClassName";
                    DataSet dataSet;
                    DataAccessor.RunSQL(DatabaseManager.GetCurrentConnection(), strSql, null, out dataSet);
                    if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in dataSet.Tables[0].Rows)
                        {
                            RefDTO refDTO = new RefDTO();
                            //ID
                            refDTO.ID = DataRowConverter.AsLong(row, "ID");
                            //ComponentID
                            refDTO.ComponentID = DataRowConverter.AsLong(row, "ComponentID");
                            //名称
                            refDTO.Name = DataRowConverter.AsString(row, "Name");
                            //显示名称
                            refDTO.DisplayName = DataRowConverter.AsString(row, "DisplayName");
                            //类名
                            refDTO.ClassName = DataRowConverter.AsString(row, "ClassName");
                            //FormId
                            refDTO.FormId = DataRowConverter.AsString(row, "FormId");
                            //程序集
                            refDTO.AssemblyName = DataRowConverter.AsString(row, "AssemblyName");
                            //URI
                            refDTO.URI = DataRowConverter.AsString(row, "URI");
                            //过滤条件
                            refDTO.Filter = DataRowConverter.AsString(row, "Filter");
                            //参照实体KEY
                            refDTO.RefEntityId = DataRowConverter.AsString(row, "RefEntityId");
                            //参照实体名
                            refDTO.RefEntityName = DataRowConverter.AsString(row, "RefEntityName");
                            //可多选
                            refDTO.IsMultiSelect = DataRowConverter.AsBool(row, "IsMultiSelect");
                            //支持多组织
                            refDTO.ForMultOrg = DataRowConverter.AsBool(row, "ForMultOrg");
                            data.Add(refDTO);
                        }

                        //批量获取参照字段
                        BatchGetRefFields(data);
                        //批量获取参照排序字段
                        BatchGetRefOrderFields(data);
                        //批量获取参照参数字段
                        BatchGetRefParams(data);
                    }
                }

                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("参照查询报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///     批量获取参照字段
        /// </summary>
        /// <param name="data"></param>
        private void BatchGetRefFields(List<RefDTO> data)
        {
            if (data == null || data.Count == 0) return;
            List<long> refIDs = new List<long>();
            foreach (RefDTO refDTO in data)
            {
                refIDs.Add(refDTO.ID);
            }

            string strSql = string.Format(@"
SELECT A.UIReference AS RefID,
       A.Name AS Name,
       A1.DisplayName AS DisplayName,
       A.RefAttributeName AS RefAttributeName,
       A.IsVisible AS IsVisible,
       A.IsKey AS IsKey,
       A.IsEdit AS IsEdit,
       A.IsName AS IsName,
       A.Sequence AS Sequence,
       A.Length AS Length,
       A.IsParent AS IsParent
FROM UBF_MD_UIRefField AS A
    LEFT JOIN [UBF_MD_UIRefField_Trl] AS A1
        ON (A1.SysMLFlag = '{1}')
           AND (A.[ID] = A1.[ID])
WHERE A.UIReference IN ( {0} )
ORDER BY A.Sequence,
         A.ID", string.Join(",", refIDs), PlatformContext.Current.Culture);
            DataSet dataSet;
            DataAccessor.RunSQL(DatabaseManager.GetCurrentConnection(), strSql, null, out dataSet);
            if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
            {
                Dictionary<long, List<RefFieldDTO>> dict = new Dictionary<long, List<RefFieldDTO>>();
                foreach (DataRow row in dataSet.Tables[0].Rows)
                {
                    RefFieldDTO refFieldDTO = new RefFieldDTO();
                    //参照ID
                    long refID = DataRowConverter.AsLong(row, "RefID");
                    //名称
                    refFieldDTO.Name = DataRowConverter.AsString(row, "Name");
                    //显示名称
                    refFieldDTO.DisplayName = DataRowConverter.AsString(row, "DisplayName");
                    //参照属性名称
                    refFieldDTO.RefAttributeName = DataRowConverter.AsString(row, "RefAttributeName");
                    //是否可见
                    refFieldDTO.IsVisible = DataRowConverter.AsBool(row, "IsVisible");
                    //是否主键字段
                    refFieldDTO.IsKey = DataRowConverter.AsBool(row, "IsKey");
                    //是否输入字段
                    refFieldDTO.IsEdit = DataRowConverter.AsBool(row, "IsEdit");
                    //是否名称显示字段
                    refFieldDTO.IsName = DataRowConverter.AsBool(row, "IsName");
                    //显示顺序
                    refFieldDTO.Sequence = DataRowConverter.AsInt(row, "Sequence");
                    //长度
                    refFieldDTO.Length = DataRowConverter.AsInt(row, "Length");
                    //父字段
                    refFieldDTO.IsParent = DataRowConverter.AsBool(row, "IsParent");
                    if (!dict.ContainsKey(refID))
                        dict.Add(refID, new List<RefFieldDTO>());
                    dict[refID].Add(refFieldDTO);
                }

                foreach (RefDTO refDTO in data)
                {
                    if (!dict.ContainsKey(refDTO.ID)) continue;
                    refDTO.RefFields = dict[refDTO.ID];
                }
            }
        }

        /// <summary>
        ///     批量获取参照排序字段
        /// </summary>
        /// <param name="data"></param>
        private void BatchGetRefOrderFields(List<RefDTO> data)
        {
            if (data == null || data.Count == 0) return;
            List<long> refIDs = new List<long>();
            foreach (RefDTO refDTO in data)
            {
                refIDs.Add(refDTO.ID);
            }

            string strSql = string.Format(@"
SELECT A.UIReference AS RefID,
       A.Name AS Name,
       A.DisplayName AS DisplayName,
       A.Sequence AS Sequence,
       A.Direction AS Direction,
       A.RefAttributeName
FROM UBF_MD_UIROrderField A
WHERE A.UIReference IN ( {0} )
ORDER BY A.ID", string.Join(",", refIDs));
            DataSet dataSet;
            DataAccessor.RunSQL(DatabaseManager.GetCurrentConnection(), strSql, null, out dataSet);
            if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
            {
                Dictionary<long, List<RefOrderFieldDTO>> dict = new Dictionary<long, List<RefOrderFieldDTO>>();
                foreach (DataRow row in dataSet.Tables[0].Rows)
                {
                    RefOrderFieldDTO refOrderFieldDTO = new RefOrderFieldDTO();
                    //参照ID
                    long refID = DataRowConverter.AsLong(row, "RefID");
                    //名称
                    refOrderFieldDTO.Name = DataRowConverter.AsString(row, "Name");
                    //显示名称
                    refOrderFieldDTO.DisplayName = DataRowConverter.AsString(row, "DisplayName");
                    //显示顺序
                    refOrderFieldDTO.Sequence = DataRowConverter.AsInt(row, "Sequence");
                    //排序方向
                    refOrderFieldDTO.Direction = DataRowConverter.AsString(row, "Direction");
                    //参照属性名称
                    refOrderFieldDTO.RefAttributeName = DataRowConverter.AsString(row, "RefAttributeName");
                    if (!dict.ContainsKey(refID))
                        dict.Add(refID, new List<RefOrderFieldDTO>());
                    dict[refID].Add(refOrderFieldDTO);
                }

                foreach (RefDTO refDTO in data)
                {
                    if (!dict.ContainsKey(refDTO.ID)) continue;
                    refDTO.RefOrderFields = dict[refDTO.ID];
                }
            }
        }

        /// <summary>
        ///     批量获取参照参数字段
        /// </summary>
        /// <param name="data"></param>
        private void BatchGetRefParams(List<RefDTO> data)
        {
            if (data == null || data.Count == 0) return;
            List<long> componentIDs = new List<long>();
            foreach (RefDTO refDTO in data)
            {
                componentIDs.Add(refDTO.ComponentID);
            }

            string strSql = string.Format(@"
SELECT A.Name AS Name,
       A.DisplayName AS DisplayName,
       A.DataType AS DataType,
       A.DefaultValue AS DefaultValue,
       A.UIReferenceComponent AS ComponentID
FROM UBF_MD_UIRefParam A
WHERE A.UIReferenceComponent IN ( {0} )
ORDER BY A.UIReferenceComponent,
         A.ID", string.Join(",", componentIDs));
            DataSet dataSet;
            DataAccessor.RunSQL(DatabaseManager.GetCurrentConnection(), strSql, null, out dataSet);
            if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
            {
                Dictionary<long, List<RefParamDTO>> dict = new Dictionary<long, List<RefParamDTO>>();
                foreach (DataRow row in dataSet.Tables[0].Rows)
                {
                    RefParamDTO refParamDTO = new RefParamDTO();
                    //参照组件ID
                    long componentID = DataRowConverter.AsLong(row, "ComponentID");
                    //名称
                    refParamDTO.Name = DataRowConverter.AsString(row, "Name");
                    //显示名称
                    refParamDTO.DisplayName = DataRowConverter.AsString(row, "DisplayName");
                    //数据类型
                    refParamDTO.DataType = DataRowConverter.AsString(row, "DataType");
                    //默认值
                    refParamDTO.DefaultValue = DataRowConverter.AsString(row, "DefaultValue");
                    if (!dict.ContainsKey(componentID))
                        dict.Add(componentID, new List<RefParamDTO>());
                    dict[componentID].Add(refParamDTO);
                }

                foreach (RefDTO refDTO in data)
                {
                    if (!dict.ContainsKey(refDTO.ComponentID)) continue;
                    refDTO.RefParams = dict[refDTO.ComponentID];
                }
            }
        }

        /// <summary>
        ///     Form查询
        /// </summary>
        /// <returns></returns>
        public ActionResult QueryForm()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                List<UIFormDTO> data = new List<UIFormDTO>();
                string queryString = Request["queryString"];
                string strLike = Request["like"];
                bool isLike;
                bool.TryParse(strLike, out isLike);
                if (!string.IsNullOrWhiteSpace(queryString))
                {
                    queryString = queryString.Trim();
                    string strSql = string.Format(@"
SELECT DISTINCT TOP 1000 
       UIForm.ID AS ID,
       UIForm.Name AS Name,
       UIFormTrl.DisplayName AS DisplayName,
       UIForm.ClassName AS ClassName,
       UIForm.UID AS FormID,
       UIForm.AssemblyName AS AssemblyName,
       UIForm.IsMain AS IsMain,
       UIForm.Width AS Width,
       UIForm.Height AS Height,
       Page.ID AS PageID,
       Page.Name AS PageName,
       PageTrl.Title AS PageTitle,
       Page.URI AS PageURI,
       Page.Application AS PageApplicaion,
       PageApplicaionTrl.Name AS PageApplicaionName,
       Menu.ID AS MenuID,
       Menu.Name AS MenuName,
       MenuTrl.DisplayName AS MenuDisplayName,
       Menu.URI AS MenuURI,
       ParentMenu.Name AS ParentMenuName,
       Menu.PageParameter AS PageParameter,
       Menu.Application AS MenuApplication,
       MenuApplicaionTrl.Name AS MenuApplicationName
FROM UBF_MD_UIForm AS UIForm
    LEFT JOIN dbo.UBF_MD_UIForm_Trl UIFormTrl
        ON UIForm.ID = UIFormTrl.ID
           AND UIFormTrl.SysMLFlag = '{0}'
    LEFT JOIN UBF_Assemble_Part AS Part
        ON Part.Component = UIForm.[UID]
    LEFT JOIN UBF_Assemble_ColumnPart AS ColumnPart
        ON ColumnPart.Part = Part.ID
    LEFT JOIN UBF_Assemble_PageColumn AS PageColumn
        ON ColumnPart.PageColumn = PageColumn.ID
    LEFT JOIN UBF_Assemble_Page AS Page
        ON PageColumn.Page = Page.ID
    LEFT JOIN dbo.UBF_Assemble_Page_Trl PageTrl
        ON PageTrl.ID = Page.ID
           AND PageTrl.SysMLFlag = '{0}'
    LEFT JOIN dbo.Base_Application PageApplicaion
        ON Page.Application = PageApplicaion.ID
    LEFT JOIN dbo.Base_Application_Trl PageApplicaionTrl
        ON PageApplicaionTrl.ID = PageApplicaion.ID
           AND PageApplicaionTrl.SysMLFlag = '{0}'
    LEFT JOIN UBF_Assemble_Menu AS Menu
        ON Page.URI = Menu.URI
           AND Menu.IsLeaf = 1
    LEFT JOIN dbo.UBF_Assemble_Menu_Trl AS MenuTrl
        ON Menu.ID = MenuTrl.ID
           AND MenuTrl.SysMLFlag = '{0}'
    LEFT JOIN UBF_Assemble_Menu AS ParentMenu
        ON Menu.Parent = ParentMenu.ID
    LEFT JOIN dbo.Base_Application MenuApplicaion
        ON Menu.Application = MenuApplicaion.ID
    LEFT JOIN dbo.Base_Application_Trl MenuApplicaionTrl
        ON MenuApplicaionTrl.ID = MenuApplicaion.ID
           AND MenuApplicaionTrl.SysMLFlag = '{0}'", PlatformContext.Current.Culture);
                    if (isLike)
                    {
                        strSql += string.Format(@" WHERE UIForm.ClassName LIKE '%{0}%'
                          OR Page.URI LIKE '%{0}%'
                          OR Page.Name LIKE '%{0}%'
                          OR Menu.Name LIKE '%{0}%'
                          OR CONVERT(VARCHAR(100), UIForm.[UID]) = '{0}'", queryString);
                    }
                    else
                    {
                        strSql += string.Format(@" WHERE UIForm.ClassName = '{0}'
                          OR Page.URI = '{0}'
                          OR Page.Name = '{0}'
                          OR Menu.Name = '{0}'
                          OR CONVERT(VARCHAR(100), UIForm.[UID]) = '{0}'", queryString);
                    }

                    strSql += " ORDER BY UIForm.Name,UIFormTrl.DisplayName";
                    DataSet dataSet;
                    DataAccessor.RunSQL(DatabaseManager.GetCurrentConnection(), strSql, null, out dataSet);
                    if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                    {
                        long i = 0;
                        foreach (DataRow row in dataSet.Tables[0].Rows)
                        {
                            i++;
                            UIFormDTO uiFormDTO = new UIFormDTO();
                            //ID
                            uiFormDTO.ID = i;
                            //名称
                            uiFormDTO.Name = DataRowConverter.AsString(row, "Name");
                            //显示名称
                            uiFormDTO.DisplayName = DataRowConverter.AsString(row, "DisplayName");
                            //类名
                            uiFormDTO.ClassName = DataRowConverter.AsString(row, "ClassName");
                            //FormId
                            uiFormDTO.FormId = DataRowConverter.AsString(row, "FormId");
                            //程序集
                            uiFormDTO.AssemblyName = DataRowConverter.AsString(row, "AssemblyName");
                            //主界面
                            uiFormDTO.IsMain = DataRowConverter.AsBool(row, "IsMain");
                            //宽度
                            uiFormDTO.Width = DataRowConverter.AsInt(row, "Width");
                            //高度
                            uiFormDTO.Height = DataRowConverter.AsInt(row, "Height");
                            //PageID
                            long pageID = DataRowConverter.AsLong(row, "PageID");
                            if (pageID > 0)
                            {
                                AssemblePageDTO pageDTO = new AssemblePageDTO();
                                //ID
                                pageDTO.ID = pageID;
                                //名称
                                pageDTO.Name = DataRowConverter.AsString(row, "PageName");
                                //标题
                                pageDTO.Title = DataRowConverter.AsString(row, "PageTitle");
                                //URI
                                pageDTO.URI = DataRowConverter.AsString(row, "PageURI");
                                //应用
                                pageDTO.Application = DataRowConverter.AsLong(row, "PageApplicaion");
                                //应用名称
                                pageDTO.ApplicationName = DataRowConverter.AsString(row, "PageApplicaionName");
                                uiFormDTO.AssemblePage = pageDTO;
                            }

                            //MenuID
                            long menuID = DataRowConverter.AsLong(row, "MenuID");
                            if (menuID > 0)
                            {
                                AssembleMenuDTO menuDTO = new AssembleMenuDTO();
                                //ID
                                menuDTO.ID = menuID;
                                //名称
                                menuDTO.Name = DataRowConverter.AsString(row, "PageName");
                                //显示名称
                                menuDTO.DisplayName = DataRowConverter.AsString(row, "MenuDisplayName");
                                //URI
                                menuDTO.URI = DataRowConverter.AsString(row, "MenuURI");
                                //父菜单名称
                                menuDTO.ParentMenuName = DataRowConverter.AsString(row, "ParentMenuName");
                                //应用
                                menuDTO.Application = DataRowConverter.AsLong(row, "MenuApplication");
                                //应用名称
                                menuDTO.ApplicationName = DataRowConverter.AsString(row, "MenuApplicationName");
                                //参数
                                menuDTO.PageParameter = DataRowConverter.AsString(row, "PageParameter");
                                uiFormDTO.AssembleMenu = menuDTO;
                            }

                            data.Add(uiFormDTO);
                        }
                    }
                }

                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("Form查询报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region 代理调试

        /// <summary>
        ///     开启事务调试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SetupTransactionDebug()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                WebSocketServiceHost service =
                    WebSocketServerManager.Instance.GetService(TransactionDebugBehavior.Path);
                if (service == null)
                    throw new DebugException("开启事务追踪失败");
                Dictionary<string, string> data = new Dictionary<string, string>();
                data.Add("port", WebSocketServerManager.ServerPort.ToString());
                data.Add("path", service.Path);
                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("开启事务调试报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///     开启代理调试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SetupProxyDoDebug()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                WebSocketServiceHost service =
                    WebSocketServerManager.Instance.GetService(ProxyDoDebugBehavior.Path);
                if (service == null)
                    throw new DebugException("开启事务追踪失败");
                Dictionary<string, string> data = new Dictionary<string, string>();
                data.Add("port", WebSocketServerManager.ServerPort.ToString());
                data.Add("path", service.Path);
                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("开启代理调试报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region OQL

        /// <summary>
        ///     Oql转为Sql
        /// </summary>
        /// <returns></returns>
        public ActionResult ConvertOqlToSql()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                string oql = Request["oql"];
                using (new BPForEngine())
                {
                    string sql = string.IsNullOrEmpty(oql) ? string.Empty : QueryHelper.ConvertOqlToSql(oql);
                    return Json(new
                    {
                        code = 0,
                        msg = "执行成功",
                        data = sql
                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Oql转为Sql报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///     执行Oql
        /// </summary>
        /// <returns></returns>
        public ActionResult RunOQL()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                string oql = Request["oql"];
                string pageParamterJsonString = Request["pageParamter"];
                PageParamter pageParamter = string.IsNullOrEmpty(pageParamterJsonString)
                    ? null
                    : JsonHelper.FromJson<PageParamter>(pageParamterJsonString);
                using (new BPForEngine())
                {
                    QueryResult<DataTable> queryResult = QueryHelper.QueryByOQL(oql, pageParamter);
                    return Json(new
                    {
                        code = 0,
                        msg = "执行成功",
                        data = JsonHelper.ToJson(queryResult)
                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error("执行Oql报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region BPSV

        /// <summary>
        ///     获取代理对象
        /// </summary>
        /// <returns></returns>
        public ActionResult GetProxyData()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                string proxyFullName = Request["proxyFullName"];
                string proxyAssemblyName = Request["proxyAssemblyName"];
                if (string.IsNullOrEmpty(proxyFullName))
                    throw new ProxyException("proxyFullName is empty");
                if (string.IsNullOrEmpty(proxyAssemblyName))
                    throw new ProxyException("proxyAssemblyName is empty");
                string strTransferRequestDataByMember = Request["transferRequestDataByMember"];
                bool transferRequestDataByMember;
                if (!bool.TryParse(strTransferRequestDataByMember, out transferRequestDataByMember))
                    transferRequestDataByMember = false;
                string strRequestDataAutoExpandLevel = Request["requestDataAutoExpandLevel"];
                int requestDataAutoExpandLevel;
                if (!int.TryParse(strRequestDataAutoExpandLevel, out requestDataAutoExpandLevel))
                    requestDataAutoExpandLevel = 1;
                string proxyType = string.Concat(proxyFullName, ",", proxyAssemblyName);
                ProxyBase proxyBase = ProxyHelper.GetProxyBaseObject(proxyType);
                if (proxyBase == null)
                    throw new ProxyException(string.Format("proxyType:{0} is not proxy base object", proxyType));
                ProxyData data = new ProxyData();
                data.ProxyType = proxyType;
                data.TransferRequestDataByMember = transferRequestDataByMember;
                data.RequestDataAutoExpandLevel = requestDataAutoExpandLevel;
                data.ProxyJsonString =
                    ProxyJsonHelper.ProxyObjectToJsonString(proxyBase, transferRequestDataByMember, true,
                        requestDataAutoExpandLevel);
                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("加载代理对象报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///     累计代理对象
        /// </summary>
        /// <returns></returns>
        public ActionResult TotalGetProxyData()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                string proxyFullName = Request["proxyFullName"];
                string proxyAssemblyName = Request["proxyAssemblyName"];
                string proxyJsonString = Request["proxyJsonString"];
                if (string.IsNullOrEmpty(proxyFullName))
                    throw new ProxyException("proxyFullName is empty");
                if (string.IsNullOrEmpty(proxyAssemblyName))
                    throw new ProxyException("proxyAssemblyName is empty");
                if (string.IsNullOrEmpty(proxyJsonString))
                    throw new ProxyException("proxyJsonString is empty");
                string strTransferRequestDataByMember = Request["transferRequestDataByMember"];
                bool transferRequestDataByMember;
                if (!bool.TryParse(strTransferRequestDataByMember, out transferRequestDataByMember))
                    transferRequestDataByMember = false;
                string strRequestDataAutoExpandLevel = Request["requestDataAutoExpandLevel"];
                int requestDataAutoExpandLevel;
                if (!int.TryParse(strRequestDataAutoExpandLevel, out requestDataAutoExpandLevel))
                    requestDataAutoExpandLevel = 1;
                string proxyType = string.Concat(proxyFullName, ",", proxyAssemblyName);
                Type loadType = ProxyHelper.GetType(proxyType);
                if (loadType == null)
                    throw new ProxyException("proxyType is incorrect");
                ProxyBase proxyBase =
                    ProxyJsonHelper.ProxyObjectFromJsonString(proxyJsonString,
                            loadType, transferRequestDataByMember) as
                        ProxyBase;
                if (proxyBase == null)
                    throw new ProxyException(string.Format("proxyType:{0} is not proxy base object", proxyType));
                ProxyData data = new ProxyData();
                data.ProxyType = proxyType;
                data.TransferRequestDataByMember = transferRequestDataByMember;
                data.RequestDataAutoExpandLevel = requestDataAutoExpandLevel;
                data.ProxyJsonString = ProxyJsonHelper.ProxyObjectToJsonString(proxyBase, transferRequestDataByMember);
                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("累计重载代理对象报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///     代理请求
        /// </summary>
        /// <returns></returns>
        public ActionResult ProxyDo()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                string proxyFullName = Request["proxyFullName"];
                string proxyAssemblyName = Request["proxyAssemblyName"];
                string proxyJsonString = Request["proxyJsonString"];
                if (string.IsNullOrEmpty(proxyFullName))
                    throw new ProxyException("proxyFullName is empty");
                if (string.IsNullOrEmpty(proxyAssemblyName))
                    throw new ProxyException("proxyAssemblyName is empty");
                if (string.IsNullOrEmpty(proxyJsonString))
                    throw new ProxyException("proxyJsonString is empty");
                string strTransferRequestDataByMember = Request["transferRequestDataByMember"];
                bool transferRequestDataByMember;
                if (!bool.TryParse(strTransferRequestDataByMember, out transferRequestDataByMember))
                    transferRequestDataByMember = false;
                string strRequestDataAutoExpandLevel = Request["requestDataAutoExpandLevel"];
                int requestDataAutoExpandLevel;
                if (!int.TryParse(strRequestDataAutoExpandLevel, out requestDataAutoExpandLevel))
                    requestDataAutoExpandLevel = 1;
                string proxyType = string.Concat(proxyFullName, ",", proxyAssemblyName);
                Type loadType = ProxyHelper.GetType(proxyType);
                if (loadType == null)
                    throw new ProxyException("proxyType is incorrect");
                ProxyBase proxyBase =
                    ProxyJsonHelper.ProxyObjectFromJsonString(proxyJsonString,
                            loadType, transferRequestDataByMember) as
                        ProxyBase;
                if (proxyBase == null)
                    throw new ProxyException(string.Format("proxyType:{0} is not proxy base object", proxyType));
                //禁用下一次服务检查
                WSSPortalSiteKeyProvider.DisableCheckOneProxy();
                MethodInfo methodInfo = proxyBase.GetType().GetMethod("Do", new Type[] { });
                if (methodInfo == null)
                    throw new ProxyException("no find Do() method in proxy object");
                try
                {
                    //反射调用
                    object result = methodInfo.Invoke(proxyBase, null);
                    return Json(new
                    {
                        code = 0,
                        msg = "执行成功",
                        data = result == null
                            ? string.Empty
                            : ProxyJsonHelper.ProxyResultToJsonString(result, transferRequestDataByMember)
                    }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return Json(new
                    {
                        code = 2,
                        msg = ExceptionHelper.GetExceptionMsg(ex)
                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error("代理请求报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region 元数据

        /// <summary>
        ///     查询元数据
        /// </summary>
        /// <returns></returns>
        public ActionResult QueryMetedata()
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                List<MetedataDTO> data = new List<MetedataDTO>();
                string strClassType = Request["classType"];
                string queryString = Request["queryString"];
                string strFocus = Request["focus"];
                string strLike = Request["like"];
                bool isFocus;
                bool.TryParse(strFocus, out isFocus);
                bool isLike;
                bool.TryParse(strLike, out isLike);
                if (!string.IsNullOrWhiteSpace(queryString))
                {
                    queryString = queryString.Trim();
                    string strSql = string.Format(@"
SELECT A.[ID] AS ID,
       A.[ClassType] AS ClassType,
       A.[FullName] AS FullName,
       A.[Name] AS Name,
       B.[DisplayName] AS DisplayName,
       A.DefaultTableName AS DefaultTableName,
       B.Description AS [Description],
       C.AssemblyName AS AssemblyName
FROM [UBF_MD_Class] AS A
    LEFT JOIN UBF_MD_Class_Trl AS B
        ON A.Local_ID = B.Local_ID
    LEFT JOIN UBF_MD_Component AS C
        ON A.MD_Component_ID = C.ID 
WHERE A.ClassType IN ({0})
      AND
      (
          B.SysMLFlag = '{1}'
          OR B.SysMLFlag IS NULL
      )", string.IsNullOrEmpty(strClassType) ? "-1" : strClassType, PlatformContext.Current.Culture);
                    if (isFocus)
                    {
                        strSql += string.Format(@" AND (A.FullName = '{0}')", queryString);
                    }
                    else
                    {
                        if (isLike)
                        {
                            strSql += string.Format(@" AND (A.Name LIKE '%{0}%' OR B.DisplayName LIKE '%{0}%')",
                                queryString);
                        }
                        else
                        {
                            strSql += string.Format(@" AND (A.Name = '{0}' OR B.DisplayName = '{0}')", queryString);
                        }
                    }

                    strSql += " ORDER BY A.Name";
                    DataSet dataSet;
                    DataAccessor.RunSQL(DatabaseManager.GetCurrentConnection(), strSql, null, out dataSet);
                    if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in dataSet.Tables[0].Rows)
                        {
                            MetedataDTO metedataDTO = new MetedataDTO();
                            metedataDTO.ID = DataRowConverter.AsString(row, "ID");
                            metedataDTO.Name = DataRowConverter.AsString(row, "Name");
                            metedataDTO.FullName = DataRowConverter.AsString(row, "FullName");
                            metedataDTO.DisplayName = DataRowConverter.AsString(row, "DisplayName");
                            metedataDTO.AssemblyName = DataRowConverter.AsString(row, "AssemblyName");
                            metedataDTO.DefaultTableName = DataRowConverter.AsString(row, "DefaultTableName");
                            metedataDTO.ClassType = DataRowConverter.AsInt(row, "ClassType");
                            metedataDTO.Description = DataRowConverter.AsString(row, "Description");
                            data.Add(metedataDTO);
                        }
                    }
                }

                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("查询实体报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        ///     获取元数据
        /// </summary>
        /// <param name="keyID"></param>
        /// <param name="parentFullName"></param>
        /// <returns></returns>
        [HttpGet]
        [OutputCache(Duration = 60, Location = OutputCacheLocation.Any)]
        public ActionResult GetMetedata(string keyID, string parentFullName)
        {
            try
            {
                CSContext.Current.Transfer();
                if (PlatformContext.Current == null || string.IsNullOrEmpty(PlatformContext.Current.EnterpriseID))
                    throw new Exception("系统未登录或登录已失效,请登录后操作");
                if (string.IsNullOrEmpty(keyID)) throw new ArgumentException("keyID不能为空", "keyID");
                string strSql = string.Format(@"
SELECT A.[ID] AS ID,
       A.[ClassType] AS ClassType,
       A.[Name] AS Name,
       A.[FullName] AS FullName
FROM [UBF_MD_Class] AS A
WHERE A.ID = '{0}'", keyID);
                TypeDTO data = null;
                DataSet dataSet;
                DataAccessor.RunSQL(DatabaseManager.GetCurrentConnection(), strSql, null, out dataSet);
                if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                {
                    DataRow row = dataSet.Tables[0].Rows[0];
                    int classType = DataRowConverter.AsInt(row, "ClassType");
                    string fullName = DataRowConverter.AsString(row, "FullName");
                    switch (classType)
                    {
                        case 1:
                            data = MetedataHelper.GetEntityMetedata(fullName);
                            break;
                        case 2:
                            data = MetedataHelper.GetPropertyTypeMetedata(fullName, parentFullName);
                            break;
                        case 3:
                            data = MetedataHelper.GetEnumMetedata(fullName);
                            break;
                        case 7:
                            data = MetedataHelper.GetBPSVMetedata(fullName);
                            break;
                    }

                    if (data != null)
                        data.ClassType = classType;
                }

                return Json(new
                {
                    code = 0,
                    msg = "执行成功",
                    data
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error("查询实体报错：" + ex.Message + "\n堆栈信息：" + ex.StackTrace);
                return Json(new
                {
                    code = 1,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion
    }
}